<?php
//创建协程的方式一
/**
echo "===start===".PHP_EOL;
\Swoole\Coroutine::create(function (){
    \Swoole\Coroutine::sleep(2);
   echo "Done".PHP_EOL;
});
echo "===start===".PHP_EOL;


//创建协程的方式二
echo "===start===222".PHP_EOL;
go(function () {
    Co::sleep(1);
    echo "Done.\n";
});
echo "===end===222".PHP_EOL;

  //创建协程的方式三 推荐
echo "===start===333".PHP_EOL;
$sched = new Swoole\Coroutine\Scheduler();
$sched->add(function () {
   Swoole\Coroutine::sleep(2);
   echo "Done".PHP_EOL;
});
echo "===end===333".PHP_EOL;
$sched->start();

 //创建协程的方式四
echo "===start===444".PHP_EOL;
Co\run(function (){
    Co::sleep(1);
    echo "Done444.\n";
});
echo "===end===444".PHP_EOL;


$a = new swoole_atomic(0);
$sched= new \Swoole\Coroutine\Scheduler();
Swoole\Coroutine::set(['max_coroutine'=>2]); //max_coroutine 含义是设置正在运行的协程个数不能超过2个
$sched->parallel(5,function ($a) {
    Swoole\Coroutine::sleep(5);
    echo "====协程===".$a->get.PHP_EOL;
    $a->addd();
},$a);
Co::set();
$sched->start();
 */

$sch = new Swoole\Coroutine\Scheduler;
$sch->add(function () use ($sch) {
    //defer用于资源的释放, 会在协程关闭之前(即协程函数执行完毕时)进行调用, 就算抛出了异常, 已注册的defer也会被执行.
    Co:defer(function (){
        echo "====释放资源===".PHP_EOL;
    });
    echo "====start=====".PHP_EOL;
    var_dump(Co::getCid());
    var_dump(Co::exists(Co::getCid()));
    var_dump(Co::getContext(Co::getCid()));
    Co::yield();//让出当前协程的执行权
    echo "=====end=====".PHP_EOL;
});

$sch->add(function () use ($sch) {
    echo "====start==22222===".PHP_EOL;
    var_dump(Co::list());
    var_dump(Co::listCoroutines());

    foreach (Co::list() as $cid) {
        if(Co::getCid()==$cid){
            continue;
        }else{
            Co::resume($cid);
        }
    }
    echo "=====end===22222==".PHP_EOL;
});
$sch->start();